package com.cardmanager.pro.scanner;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.jh.common.utils.CommonConstants;
import com.cardmanager.pro.executor.BaseExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cardmanager.pro.business.ConsumeTaskPOJOBusiness;
import com.cardmanager.pro.pojo.ConsumeTaskPOJO;

/**
 * 执行异常任务表
 * @author lichengying
 */
@Configuration
@Controller
@EnableScheduling
public class ConsumeTaskScanner extends ApplicationObjectSupport{

	private final Logger LOG = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseExecutor baseExecutor;

	@Autowired
	private ConsumeTaskPOJOBusiness consumeTaskPOJOBusiness;
	
	@Value("${schedule-task.on-off}")
	private String scanOnOff;
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/test")
	public @ResponseBody Object test(HttpServletRequest request){
		List<ConsumeTaskPOJO> consumeTaskPOJOs = this.findTaskType2AndTaskStatus0RepaymentTask();
		this.executeTask(consumeTaskPOJOs);
		return "OK";
	}

	/**
	 * 执行消费异常定时任务
	 * 1：用户恶意操作，卡内余额不足两次扣款，扣款当天第一次扣款成功，第二次扣款失败，将第一笔消费保存到消费异常表中，等待本次任务执行，后续任务将不执行；
	 * 2：用户惯性操作，卡内余额不足两次扣款，用户初次余额足够扣款，前面任务执行成功，某次用户将卡内余额消费至不足以当天二次扣款，将第一笔消费保存到消费异常表中，等待本次任务执行，后续任务将不执行；
	 * 每小时执行一次
	 */
//	@Scheduled(cron = "0 */1 * * *")
	@Scheduled(cron = "0 0 * * * ?")//每小时执行一次
	public void autoScanRepaymentTask() {
		LOG.debug("=======执行异常任务开始=========");
		List<ConsumeTaskPOJO> list = this.findTaskType2AndTaskStatus0RepaymentTask();
		if (list.size() > 0) {
			this.executeTask(list);
		}

		LOG.debug("=======执行异常任务结束=========");
	}

	/**
	 * 获取当天及当前时间之前批量生成的未执行消费任务
	 * @return
	 */
	public List<ConsumeTaskPOJO> findTaskType2AndTaskStatus0RepaymentTask(){
		return consumeTaskPOJOBusiness.findTaskType2AndTaskStatus0RepaymentTask();
	}

	public void executeTask(List<ConsumeTaskPOJO> list){
		LOG.debug("========代还还款任务执行start=========");
		for (ConsumeTaskPOJO pojo : list) {
			Map<String,String> map = baseExecutor.paymentRepaymentTask(String.valueOf(pojo.getAmount()),pojo.getUserId(),
					pojo.getCreditCardNumber(),pojo.getChannelId(),String.valueOf(pojo.getRate()),String.valueOf(pojo.getRealAmount()),pojo.getChannelTag());
			LOG.debug("========代还还款任务执行end=========");

			String respCode = map.getOrDefault("resp_code","0");
			String code = map.getOrDefault("code","0");
			if(respCode.equals(CommonConstants.SUCCESS)){
				if(pojo.getAmount().compareTo(pojo.getRealAmount()) != 0){
					if(!code.equals("1")){
						LOG.debug("========task-passageway-fail=========");
						pojo.setTaskStatus(2);//执行失败
						pojo.setReturnMessage("通道返回失败!");
						pojo.setErrorMessage((String) map.getOrDefault("code","0"));
						pojo.setRealAmount(BigDecimal.ZERO);
						consumeTaskPOJOBusiness.save(pojo);
					}else{
						LOG.debug("========task-passageway-success=========");
						pojo.setTaskStatus(1);
						pojo.setOrderCode(pojo.getOrderCode());
						pojo.setReturnMessage("执行成功!");
						pojo = consumeTaskPOJOBusiness.save(pojo);
					}
				}
			}else{
				//系统异常
				LOG.debug("========task-passageway-error=========");
				pojo.setTaskStatus(4);
				pojo.setReturnMessage("通道执行异常！");
				pojo.setErrorMessage((String) map.getOrDefault("code","0"));
				pojo.setRealAmount(BigDecimal.ZERO);
				consumeTaskPOJOBusiness.save(pojo);
			}
		}

	}
	
}
